package uoc.biblioteca.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import uoc.biblioteca.mappings.object.UserVo;
import uoc.biblioteca.struts.form.ReadMilleniumForm;
import uoc.biblioteca.struts.form.SendMailForm;
import uoc.biblioteca.util.SendMail;

public class SendMailAction extends BaseAction {
    
   
	private static final Log log = LogFactory.getLog(SendMailAction.class);
	
	/** 
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {
    
		
		SendMailForm  sendMailForm = (SendMailForm ) form;
		
			try{
				
				 //Comprobar si la session esta guardada
				UserVo userLogin = obtenerUserSession(request);
				if(userLogin==null){
					request.getSession().setAttribute("ERROR","\n" +NO_USER_SESSION);
					return mapping.findForward("errorNotUser");
				}
			    
				if (("sendMail").equals(sendMailForm.getAction())){
			    	return sendMail(mapping, form, request, response);
			    }
				
				else{
					return sendMail(mapping, form, request, response);
				}
			
			}
			catch (Exception e) {
				e.printStackTrace();
				log.error("Error: ", e);
				request.getSession().setAttribute("ERROR","\n" +e.toString()  );
				return mapping.findForward("error");
			}
			
	}

	//Enviar mail	
	public ActionForward sendMail(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {
		SendMailForm  sendMailForm = (SendMailForm ) form;
		
		
		try{
			
			//Get the servers upload directory real path name
	        //String filePath = getServlet().getServletContext().getRealPath("/") +"properties";
	        String filePath ="/opt/local/home_biblioteca/configHome/adquisicions/properties";
	        
			SendMail sendMail = new SendMail();
			sendMail.setUrlProperties(filePath);
			sendMail.sendMail("title test mail","text test ..... .... .. .","javierpoza@gmail.com");
			
			return mapping.findForward("sendMailOk");
		}
		catch (Exception e) {
			e.printStackTrace();
			log.error("Error: ", e);
			request.getSession().setAttribute("ERROR","\n" +e.toString()  );
			return mapping.findForward("error");
		}
	}
	
	
	
}